package cn.springboot.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public void setString(String key,String value){
        this.setObject(key,value,null);
    }
    public void setString(String key,String value,long time){
        this.setObject(key,value,time);
    }

    public void setList(String key,List listValue){
        this.setObject(key,listValue,null);
    }
    //记得加上有效期
    public  void setObject(String key,Object value,Long time){
        //redis的几种数据类型
        if(StringUtils.isEmpty(key) || value== null){
            return;
        }
        //判断是String类型

        if(value instanceof String){
            String strValue=(String) value;
            stringRedisTemplate.opsForValue().set(key,strValue);
           if(time!=null){
               stringRedisTemplate.opsForValue().set(key,strValue,time, TimeUnit.SECONDS);
           }

            return;
        }
        //存放list类型
        if(value instanceof List){
             List<String> listvalue= (List<String>) value;
            for (String s :
                    listvalue) {
                stringRedisTemplate.opsForList().leftPush(key,s);
                return;
            }

        }


    }
    public String getStringKey(String key){
       return stringRedisTemplate.opsForValue().get(key);
    }
}
